
import { ApiFilled, PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns, ProDescriptionsItemProps } from '@ant-design/pro-components';
import {
  FooterToolbar,
  ModalForm,
  PageContainer,
  ProDescriptions,
  ProFormText,
  ProFormTextArea,
  ProTable,
} from '@ant-design/pro-components';
import { FormattedMessage, Link, useIntl } from '@umijs/max';
import { Button, Drawer, Input, Switch, message } from 'antd';
import React, { useRef, useState } from 'react';

import { history } from 'umi';
//services

import { addPaperUsingPost, deletePaperUsingPost, listPaperByPageUsingGet, updatePaperUsingPost } from '@/services/backend1/paperController';
import { jsonToQuestionScores } from '@/utils/jsonUtil';
// import PaperEditor from '../PaperEditor/PaperEditor';

/**
 * @en-US new paper
 * @zh-CN 添加节点
 * @param fields
 */
const handleAdd = async (fields: API.Paper) => {
  const hide = message.loading('正在添加');
  try { 
    
    await addPaperUsingPost({
      name:fields.name,
      questions: jsonToQuestionScores(fields.questions),
     });
    hide(); 
    message.success('添加成功');
    return true;
  } catch (error: any) {
    hide();
    message.error('添加失败,请重试',error.message);
    return false;
  }
};


/**
 * @en-US Update node
 * @zh-CN 更新节点
 *
 * @param fields
 */
const handleUpdate = async (paper: API.Paper) => {
  const hide = message.loading('updating');
  try {
    await updatePaperUsingPost({
      id: paper.id,
      name: paper.name,
      questions: jsonToQuestionScores(paper.questions),
    });
    hide();

    message.success('update paper is successful');
    return true;
  } catch (error:any) {
    hide();
    message.error('update paper failed, please try again!',error.message);
    return false;
  }
};

/**
 *  Delete node
 * @zh-CN 删除节点
 *
 * @param papers
 */
const handleRemove = async (selectedRows: API.Paper[]) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;
  try {
    await deletePaperUsingPost({
      ids: selectedRows.map((paper:any) => paper.id),
    });
    hide();
    message.success('删除成功,正在刷新');
    return true;
  } catch (error:any) {
    hide();
    message.error('删除失败,请重试',error.message);
    return false;
  }
};

const PaperManagement: React.FC = () => {
  /**
   * @en-US Pop-up window of new window
   * @zh-CN 新建窗口的弹窗
   *  */
  const [createModalOpen, handleCreateModalOpen] = useState<boolean>(false);
  /**
   * @en-US The pop-up window of the distribution update window
   * @zh-CN 分布更新窗口的弹窗
   * */
  const [editorOpen, handleEditorOpen] = useState<boolean>(false);

  const [showDetail, setShowDetail] = useState<boolean>(false);

  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<API.Paper>();
  const [selectedRowsState, setSelectedRows] = useState<API.Paper[]>([]);

  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */
  const intl = useIntl();

  const columns: ProColumns<API.Paper>[] = [
    {
      title: "试卷名称",
      dataIndex: 'name',
      render: (dom, entity) => {
        return (
          <a
            onClick={() => {
              setCurrentRow(entity);
              setShowDetail(true);
            }}
          >
            {dom}
          </a>
        );
      },
    },
    {
      title: 'ID',
      dataIndex: 'id',
      // sorter: true,
      hideInForm: true,
      renderText: (val: string) =>
        `${val}`,
    },
    // {
    //   title: 'questions',
    //   dataIndex: 'questions',
    //   // sorter: true,
    //   hideInForm: true,
    //   renderText: (val: string) =>
    //     `${val}`,
    // },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a
          key="config"
          onClick={() => {
            // 跳转
            history.push(`/paper/edit/${record.id}`);
          }}
        >
          <span>Edit</span>
        </a>,
        // <Link key="config" to={`./edit?id=${record.id}`}>
        //   <span>Edit</span>
        // </Link>,
       
      ],
    },
  ];

  
  return (
    
    <PageContainer>
      <ProTable<API.Paper, API.listPaperByPageUsingGETParams>
        headerTitle={'查询表格'}
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleCreateModalOpen(true);
            }}
          >
            <PlusOutlined /> <span>New</span>
          </Button>,
        ]}
        
        request={
          async(params,sort,filter,)=>{
            const msg =await listPaperByPageUsingGet({
              ...params
            });
            return {
              data: msg.data?.records,
              success: msg.message=='ok',
              total: msg.data?.total,
            };
          }}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              <span>已选择</span>{' '}
              <a style={{ fontWeight: 600 }}>{selectedRowsState.length}</a>{' '}
              <span>项</span>
              &nbsp;&nbsp;
            </div>
          }
        >
          <Button type='primary'
            onClick={async () => {
              await handleRemove(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            <span>批量删除</span>
          </Button>
          
        </FooterToolbar>
      )}

      <ModalForm
        title={'新建试卷'}
        width="400px"
        open={createModalOpen}
        onOpenChange={handleCreateModalOpen}
        onFinish={async (value) => {
          const success = await handleAdd(value as API.Paper);
          if (success) {
            handleCreateModalOpen(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
      >
        <ProFormText
          rules={[
            {
              required: true,
              message: '试卷名称是必填项',
            },
          ]}
          width="md"
          name="name"
        />
        
      </ModalForm>
      
      {/* <PaperEditor
        onSubmit={async (value) => {
          const success = await handleUpdate(value);
          if (success) {
            handleEditorOpen(false);
            setCurrentRow(undefined);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          handleEditorOpen(false);
          if (!showDetail) {
            setCurrentRow(undefined);
          }
        }}
        editorOpen={editorOpen}
        values={currentRow || {}}
      />  */}

      <Drawer
        width={600}
        open={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.name && (
          <ProDescriptions<API.Paper>
            column={2}
            title={currentRow?.name}
            request={async () => ({
              data: currentRow || {},
            })}
            params={{
              id: currentRow?.name,
            }}
            columns={columns as ProDescriptionsItemProps<API.Paper>[]}
          />
        )}
      </Drawer>
    </PageContainer>
  
  );
};

export default PaperManagement;
